// pages/student/course-square/course-square.js
import { courses, courseCategories, difficultyMap } from '../../../utils/mockData.js'

Page({
  data: {
    categories: courseCategories,
    selectedCategory: 0,
    searchKeyword: '',
    courses: [],
    filteredCourses: []
  },
  
  onLoad() {
    this.loadData()
  },
  
  onPullDownRefresh() {
    this.loadData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },
  
  loadData() {
    // 处理课程数据,添加难度文本
    const processedCourses = courses.map(course => ({
      ...course,
      difficultyText: difficultyMap[course.difficulty_level] || '未知'
    }))
    
    this.setData({
      courses: processedCourses,
      filteredCourses: processedCourses
    })
  },
  selectCategory(e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      selectedCategory: id
    })
    this.filterCourses()
  },
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.filterCourses()
  },
  filterCourses() {
    const { searchKeyword, selectedCategory } = this.data
    let filtered = this.data.courses
    
    if (searchKeyword) {
      filtered = filtered.filter(course => 
        course.title.includes(searchKeyword) || 
        course.teacher.name.includes(searchKeyword)
      )
    }
    
    if (selectedCategory > 0) {
      const category = this.data.categories.find(c => c.id === selectedCategory)
      if (category) {
        filtered = filtered.filter(course => course.category === category.name)
      }
    }
    
    this.setData({
      filteredCourses: filtered
    })
  },
  goToCourseDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/student/course-detail/course-detail?id=${id}`
    })
  }
})
